<template>
<div :class="[$style.container]">
  <div :class="[$style.header]">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/download' }">下载首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{title}}</el-breadcrumb-item>
    </el-breadcrumb>
  </div>
  <div :class="[$style.body]">
    <el-table :data="renderedItems" stripe size="small" style="width: 100%">
      <el-table-column prop="name" label="文件名">
        <template #default="{row}">
          <span :class="[$style.docIcon]"><doc-icon :data="{ name: row.data.docName }"></doc-icon></span>
          <span>{{row.data.docName}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="size" label="大小" width="160px">
        <template #default="{ row }">
          <span>{{row.data.done | size}}</span>/<span>{{row.data.size | size}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" :width="220">
        <template #default="{row}">
          <span v-if="['pending', 'resume'].includes(row.status)">
            <span class="mr-1"><i class="el-icon-time"></i></span>
            <span>{{statusText(row.status)}}</span>
          </span>
          <span v-else-if="row.status === 'success'">
            <span class="text-success mr-1"><i class="el-icon-circle-check"></i></span>
            <span>{{statusText(row.status)}}</span>
          </span>
          <span v-else>
            <div>
              <el-progress :percentage="getProgress(row)" :stroke-width="4" :show-text="false"
                :status="row.status === 'fail' ? 'exception' : undefined"></el-progress>
            </div>
            <div>
              <span v-if="row.status === 'downloading'">
                <span>{{row.data.speed | size}}/s</span>
                -
                <span>剩余时间: {{leftTime(row)}}</span>
              </span>
              <span v-else>
                 <span>{{statusText(row.status)}}</span>
                 <el-tooltip class="item" effect="dark" :content="row.data.errMsg" v-if="row.status === 'fail'">
                  <span class="text-warning ml-2"><i class="el-icon-warning-outline"></i></span>
                </el-tooltip>
              </span>
            </div>
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="action" label="操作" width="180" fixed="right">
        <template #default="{row}">
          <div style="font-size: 14px;">
            <el-tooltip content="开始" class="ml-2" :open-delay="750" v-if="row.status === 'pause'">
              <span :class="[$style.icon]" @click="onResume(row)"><i class="el-icon-video-play"></i></span>
            </el-tooltip>
            <el-tooltip content="暂停" class="ml-2" :open-delay="750" v-if="row.status === 'downloading'">
              <span :class="[$style.icon]" @click="onPause(row)"><i class="el-icon-video-pause"></i></span>
            </el-tooltip>
            <el-tooltip content="重试" class="ml-2" :open-delay="750" v-if="row.status === 'fail'">
              <span :class="[$style.icon]" @click="onRetry(row)"><i class="el-icon-refresh"></i></span>
            </el-tooltip>
            <el-tooltip content="打开所在目录" class="ml-2" :open-delay="750">
              <span :class="[$style.icon]" @click="onOpen(row)"><i class="el-icon-search"></i></span>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @current-change="onCurrentChange" :current-page="pagination.page"
      :page-size="pagination.size"
      layout="prev, pager, next, jumper"
      :total="pagination.total">
    </el-pagination>
  </div>
</div>
</template>

<script lang="ts">

import { TransportItem } from '@/plugins/downloader/src/Transporter'
import { remote } from 'electron'
import { Vue, Component, Provide, Watch, Ref, Prop } from 'vue-property-decorator'
import path from 'path'

const statusMap: any = {
  pending: '等待中',
  downloading: '下载中',
  success: '已完成',
  fail: '下载失败',
  pause: '已暂停',
  resume: '恢复中'
}

interface SubItem {
  status: 'pending' | 'downloading' | 'success' | 'fail' | 'pause' | 'resume';
  data: TransportItem;
}

@Component
export default class DoanloadDetail extends Vue {
  $style!: any

  @Prop(String) id!: string

  pagination = {
    page: 1,
    size: 10,
    total: this.items.length
  }

  statusText (status: string) {
    return statusMap[status] || status
  }

  leftTime (row: any) {
    const { data } = row
    const { size = 0, done = 0, speed = 0 } = data
    if (!speed) return '-'
    const duration = Math.max((size - done) / speed, 0)
    const s = Math.floor(duration % 60)
    const m = Math.floor((duration / 60) % 60)
    const h = Math.floor(duration / 3600)
    const f = (t: any) => ('0' + t).slice(-Math.max(2, String(t).length))
    return f(h) + ':' + f(m) + ':' + f(s)
  }

  onResume (row: any) {
    this.$downloader.transporter.resumeItem(row.data)
  }

  onPause (row: any) {
    const { data } = row
    this.$downloader.transporter.pauseItem(row.data)
  }

  onRemove (row: any) {
    // this.$confirm('确认要删除该下载项?', '确认').then(() => {
    //   this.$downloader.remove(row?.id)
    // }).catch(() => {
    //   // ignore
    // })
  }

  onRetry (row: any) {
    const { data } = row
    this.$downloader.transporter.retryItem(row.data)
  }

  onOpen (row: any) {
    const { shell } = remote
    const p = path.dirname(row.data?.localPath)
    shell.openPath(p)
  }

  onClear () {
    // this.$confirm('确认要清空所有下载项?', '确认').then(() => {
    //   this.$downloader.removeAll()
    // }).catch(() => {
    //   // ignore
    // })
  }

  onCurrentChange (page: number) {
    this.pagination.page = page
  }

  get items () {
    const downloadId = this.id
    const transpoter = this.$downloader.transporter
    const pending = transpoter.pendingQueue.filter(v => v.downloadId === downloadId).map(v => ({ status: 'pending', data: v }))
    const downloading = transpoter.downloadingQueue.filter(v => v.downloadId === downloadId).map(v => ({ status: 'downloading', data: v }))
    const done = transpoter.doneQueue.filter(v => v.downloadId === downloadId).map(v => ({ status: 'success', data: v }))
    const error = transpoter.errorQueue.filter(v => v.downloadId === downloadId).map(v => ({ status: 'fail', data: v }))
    const pause = transpoter.pauseQueue.filter(v => v.downloadId === downloadId).map(v => ({ status: 'pause', data: v }))
    const resume = transpoter.resumeQueue.filter(v => v.downloadId === downloadId).map(v => ({ status: 'resume', data: v }))
    return [...downloading, ...pause, ...resume, ...pending, ...done, ...error]
  }

  get title () {
    const downloadId = this.id
    return this.$downloader.queue.find(v => v.id === downloadId)?.name
  }

  getProgress (row: any) {
    const { data } = row
    return 100 * data.done / (data.size || 1)
  }

  get renderedItems () {
    const { page, size } = this.pagination
    const s = (page - 1) * size
    const e = s + size
    return this.items.slice(s, e)
  }
}
</script>

<style lang="scss" module>
@import "~@/styles/vars.scss";

$header-height: 40px;

.container {
  height: 100%;
  background-color: #fff;
}

.header {
  height: 48px;
  padding: 0 12px;
  border-bottom: 1px solid $border-split-color;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  justify-content: flex-start;
}

.body {
  box-sizing: border-box;
  padding: 12px;
  height: calc(100% - 48px - 40px);
  overflow: auto;
}

.icon {
  &:hover {
    cursor: pointer;
    opacity: .8;
  }
}

.docIcon {
  font-size: 18px;
  margin-right: 12px;
  color: $color-primary;
}
</style>
